package com.sduept.nwld.dataview.controller.core;

import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.cim.ledger.excetpion.ManagementUnitException;
import com.sduept.cim.ledger.model.ManagementUnitDict;
import com.sduept.cim.ledger.services.ManagementUnitService;
import com.sduept.nwld.dataserver.util.LibTreeNode;
import com.sduept.utils.PingYinUtil;
import org.apache.commons.lang3.StringUtils;
import org.primefaces.PrimeFaces;
import org.primefaces.event.NodeExpandEvent;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.util.*;

@Named
@ViewScoped
public class OpSubCompanyDepartSelectorController extends AbstractController {
	//TODO: 该类 更换了ManagementUnitService 实现，需要优化，暂时把错误去掉
	/**
	 * 
	 */
	private static final long serialVersionUID = -5097893345002636153L;
	@Autowired
	private ManagementUnitService unitService;
	private TreeNode opSubCompanyTree; // 运维单位树
	private TreeNode selectedNode;
	
	private String dept;
	/**
	 * 所有的运维单位
	 */
	private List<ManagementUnitDict> allMaintenanceUnits;
	/**
	 * 所有的检修范围,<id,ManagementUnitDict>
	 */
	private Map<String,ManagementUnitDict> maintenanceScopesMap = new HashMap<String, ManagementUnitDict>();
	
	@PostConstruct
	public void init() {
		try {
			allMaintenanceUnits = unitService.getAllMaintenanceManagements();
			List<ManagementUnitDict> allMaintenanceScopes = unitService.getAllMaintenanceScopes();
			for (ManagementUnitDict unit : allMaintenanceScopes) {
				maintenanceScopesMap.put(unit.getId(), unit);
			}
			genOpSubCompanyTree();
		} catch (ManagementUnitException e) {
			e.printStackTrace();
			addErrorMessage("获取所有的运维单位失败");
		}
	}
	
	/**
	 * 构造运维单位树
	 */
	public void genOpSubCompanyTree() {
		opSubCompanyTree = new LibTreeNode("Root", null);
		try {
			// 组织机构的根节点，即南方电网
			String rootName = unitService.getManagementUnitRoot();
			if(StringUtils.isEmpty(rootName)) {
				rootName = "南方电网";
			}
			LibTreeNode root = new LibTreeNode("root",rootName, opSubCompanyTree);
			List<ManagementUnitDict> firstLevelUnits = getFirstLevelUnitsFromList();
			for (ManagementUnitDict unit : firstLevelUnits) {
				new LibTreeNode("maintenanceScope",unit, root);
			}
			root.setExpanded(true);
		} catch (ManagementUnitException e) {
			e.printStackTrace();
			addErrorMessage("获取部门根节点失败");
		}
	}
	/**
	 * 从所有的运维单位中，获取一级单位，即如果某记录的父单位类型为检修范围，则该父部门设为运维单位的一级单位
	 * @return
	 */
	private List<ManagementUnitDict> getFirstLevelUnitsFromList() {
		Set<ManagementUnitDict> firstLevelUnits = new HashSet<ManagementUnitDict>();
		for (ManagementUnitDict unit : allMaintenanceUnits) {
			if(maintenanceScopesMap.containsKey(unit.getPid())) {
				firstLevelUnits.add(maintenanceScopesMap.get(unit.getPid()));
			}
		}
		List<ManagementUnitDict> list = new ArrayList<ManagementUnitDict>();
		list.addAll(firstLevelUnits);
		sort(list);
		return list;
	}
	
	/**
	 * 将ManagementUnitDict按ordered从高到低排序
	 * @param List<ManagementUnitDict>
	 */
	private void sort(List<ManagementUnitDict> list) {
		Collections.sort(list,new Comparator<ManagementUnitDict> () {
			@Override
			public int compare(ManagementUnitDict o1, ManagementUnitDict o2) {
				return o2.getOrdered()-o1.getOrdered();
			}
		});
	}
	
	/**
	 * 运维单位
	 */
	public List<String> completeMaintenanceUnit(String query) {
		List<String> result = new ArrayList<String>();
		for (ManagementUnitDict dept : allMaintenanceUnits) {
			String pName = PingYinUtil.getPingYinHeader(dept.getName());
			if(pName.contains(query)) {
				result.add(dept.getName());
			}
		}
		return result;
	}
	
	/**
	 * 运维单位树增加快速筛选功能，根据查询的部门重新构造树
	 * @param event
	 */
	public void autoCompleteOpTree(SelectEvent event) {
		Object item = event.getObject();
		if (null != item) {
			opSubCompanyTree = new DefaultTreeNode();
			try {
				ManagementUnitDict unit = unitService.getManagementUnitByName(item.toString());
				new LibTreeNode("maintenanceUnit",unit, opSubCompanyTree);
			} catch (ManagementUnitException e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 清空快速筛选条件时，需要重新构造树
	 */
	public void refreshOpTree() {
		dept = null;
		selectedNode = null;
		genOpSubCompanyTree();
	}
	
	public void selectOpDepart() {
		if("maintenanceUnit".equals(selectedNode.getType())||"maintenanceScope".equals(selectedNode.getType())) {
			ManagementUnitDict select = (ManagementUnitDict) selectedNode.getData();
			PrimeFaces.current().dialog().closeDynamic(select);
		} else {
			selectedNode = null;
			alertErrorMessage("请选择正确的部门");
			genOpSubCompanyTree();
		}
	}
	
	/**
	 * 选中树节点
	 * @param event
	 */
	public void onNodeSelect(NodeSelectEvent event) {
		selectedNode = event.getTreeNode();
	}
	
	/**
	 * 展开运维单位树节点
	 * @param event
	 */
	public void onNodeExpand(NodeExpandEvent event) {
		TreeNode selectedNode = event.getTreeNode();
		if("root".equals(selectedNode.getType())) {
			List<ManagementUnitDict> childs = getFirstLevelUnitsFromList();
			for (ManagementUnitDict unit : childs) {
				new LibTreeNode("maintenanceScope",unit, selectedNode);
			}
		} else if ("maintenanceScope".equals(selectedNode.getType())) {
			ManagementUnitDict select = (ManagementUnitDict) selectedNode.getData();
			List<ManagementUnitDict> childs = getUnitsByPidFromList(select.getId());
			for (ManagementUnitDict unit : childs) {
				new LibTreeNode("maintenanceUnit",unit, selectedNode);
			}
		}
	}

	/**
	 * 根据pid，从allMaintenanceUnits中获取pid符合条件的记录
	 * @param pid
	 * @return 
	 */
	private List<ManagementUnitDict> getUnitsByPidFromList(String pid) {
		List<ManagementUnitDict> result = new ArrayList<ManagementUnitDict>();
		for (ManagementUnitDict unit : allMaintenanceUnits) {
			if(pid.equals(unit.getPid())) {
				result.add(unit);
			}
		}
		sort(result);
		return result;
	}
	
	public String getDept() {
		return dept;
	}

	public void setDept(String dept) {
		this.dept = dept;
	}

	public TreeNode getOpSubCompanyTree() {
		return opSubCompanyTree;
	}

	public void setOpSubCompanyTree(TreeNode opSubCompanyTree) {
		this.opSubCompanyTree = opSubCompanyTree;
	}

	public TreeNode getSelectedNode() {
		return selectedNode;
	}

	public void setSelectedNode(TreeNode selectedNode) {
		this.selectedNode = selectedNode;
	}

}
